// ==UserScript==
// @name         roam capture
// @namespace    https://github.com/luyanfei
// @version      0.1
// @description  capture content to org roam notes
// @author       luyanfei
// @include      *://time.geekbang.org/column/*
// @connect      *.geekbang.org
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_download
// @grant        GM_xmlhttpRequest
// @icon         
// ==/UserScript==

function handleSlateType(el) {
    let slateType = el.dataset.slateType;
    if (slateType === 'paragraph' || slateType === 'list-line' || slateType === 'block-quote') {
        return el.textContent.trim();
    } else if (slateType === 'list') {
        let result = '';
        let seq = 1;
        for (let item of el.childNodes) {
            let itemContent = handleSlateType(item);
            //console.log('itemContent:' + itemContent);
            if (itemContent && itemContent.length > 0) {
                result += seq + '. ' + itemContent + '\n\n';
                seq++;
            }
        }
        return result;
    } else if (slateType === 'heading') {
        return '** ' + el.textContent.trim();
    } else if (slateType === 'pre') {
        let content = "";
        //定位到代码块，逐行提取文本
        let inner = el.querySelector('[data-origin="pm_code_preview"]');
        for (let child of Array.from(inner.children)) {
            content += child.textContent + "\n";
        }
        console.log(encodeURIComponent(content));
        return "#+begin_src\n" + content + "#+end_src\n";
    } else if (slateType === 'image') {
        let first = el.firstElementChild;
        if (!first || first.tagName.toLowerCase() !== 'img') {
            console.log('slateType is "image", but first child is not "img"!');
            return "";
        }
        let imgurl = first.getAttribute('src');
        let lastQ = imgurl.lastIndexOf('?');
        if (lastQ !== -1) {
            imgurl = imgurl.substr(0, lastQ);
        }
        let filename = imgurl.substr(imgurl.lastIndexOf('/') + 1);
        GM_download(imgurl, filename);
        return "[[./images/" + filename + "]]";
    }
    return "unknown slate type."
}

var previous = null;

function add_capture_listener(div) {
    div.addEventListener('click', () => {
        if (!previous) {
            alert('previous is null.');
            return;
        }
        var fragment = previous;
        if (fragment) {
            let content = "";
            let nodes = Array.from(fragment.children)
            for (let ele of nodes) {
                content += handleSlateType(ele) + "\n\n";
            }
            //console.log(content);
            location.href = 'org-protocol://roam-ref?template=d&ref='
                + encodeURIComponent(location.href)
                + '&title='
                + encodeURIComponent(document.title)
                + '&body='
                + encodeURIComponent(content);
            console.log('content:' + content);
            div.style.display = 'none';
        }
    });
    console.log('script executed.');
}

(function() {
    var div = document.createElement('div');
    div.style.padding = '3px';
    div.style.margin = '3px';
    div.style.backgroundColor = '#eee';
    div.style.cursor = 'pointer';
    div.style.position = 'absolute';
    div.style.display = 'none';
    div.appendChild(document.createTextNode('抓取'));
    document.body.appendChild(div);
    add_capture_listener(div);

    document.onpointerup = function() {
        let selection = document.getSelection();
        let selectedText = selection.toString();
        if (selectedText !== "") {
            let rect = selection.getRangeAt(0).getBoundingClientRect();
            div.style.top = `calc(${rect.bottom}px - 48px)`;
            div.style.left = `calc(${rect.left}px + 180px)`;
            div.style.display = 'block';
        } else {
            if (div.style.display === 'block') {
                div.style.display = 'none';
            }
        }
    }

    document.addEventListener('selectionchange', () => {
        let sel = document.getSelection();
        let text = sel.toString();
        //console.log('seletion text length:' + text.length);
        if (text.length !== 0) {
            previous = sel.getRangeAt(0).cloneContents();
        }
    })

})();
